package net.xt.testthread;

import java.util.concurrent.*;

/**
 * 测试多线程并发执行
 */
public class TestConcurrent {

    // 定义三个方法，每个执行耗时5秒
    // 使用多线程模拟三个方法并发执行

    public void m1() {
        System.out.println("执行m1方法。。。。。。" + Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m1方法结束");
        System.out.println("====================");
    }

    public void m2() {
        System.out.println("执行m2方法。。。。。。" + Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m2方法结束");
        System.out.println("====================");
    }

    public void m3() {
        System.out.println("执行m3方法。。。。。。" + Thread.currentThread().getName());
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("m3方法结束");
        System.out.println("====================");
    }

    public static void main(String[] args) throws InterruptedException {
        System.out.println("begin");
        for (int i = 0; i < 100; i++) {
            Thread.sleep(100);
            System.out.print("process:" + (i + 1) + "%\r");
        }
        System.out.println();
        System.out.println("end");

//        TestConcurrent testConcurrent = new TestConcurrent();
//
//        try {
//            long startTime = System.currentTimeMillis();
//
//            CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
//                testConcurrent.m1();
//            });
//            CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> {
//                testConcurrent.m2();
//            });
//            CompletableFuture<Void> future3 = CompletableFuture.runAsync(() -> {
//                testConcurrent.m3();
//            });
//            // 多线程并发执行三个方法，并统计耗时时间
//            CompletableFuture<Void> future = CompletableFuture.allOf(future1, future2, future3);
//            future.join();
//            System.out.println("总共用时：" + (System.currentTimeMillis() - startTime) / 1000 + "秒");
//
//            // 主线程等待
//            TimeUnit.SECONDS.sleep(15);
//            System.out.println("主线程结束");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

}
